package com.duqc.util;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;

/**
 * @ClassName ThreadPoolUtil
 * @Description DES加解密
 * @Author duqc
 * @Date 2021/4/7
 **/
@Slf4j
public class DESUtil {

    private static final String DES = "DES";

    private DESUtil() {

    }

    /**
     * 加密
     *
     * @param src
     * @param key
     * @return String
     */
    public static String encrypt(String src, String key) {
        try {
            SecureRandom sr = new SecureRandom();
            DESKeySpec dks = new DESKeySpec(key.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
            SecretKey secretKey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance(DES);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, sr);
            return Base64.getEncoder().encodeToString(cipher.doFinal(src.getBytes()));
        } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException |
                BadPaddingException | InvalidKeySpecException | IllegalBlockSizeException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 解密
     *
     * @param src
     * @param key
     * @return String
     */
    public static String decrypt(String src, String key) {
        try {
            SecureRandom sr = new SecureRandom();
            DESKeySpec dks = new DESKeySpec(key.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
            SecretKey secretKey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance(DES);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, sr);
            return new String(cipher.doFinal(Base64.getDecoder().decode(src)));
        } catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException |
                NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeySpecException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    public static void main(String[] args) {
        String encrypt = encrypt("duqc@2021", "qwertyuiop");
        log.info(encrypt);
        String decrypt = decrypt(encrypt, "qwertyuiop");
        log.info(decrypt);
    }
}
